var mysql = require('mysql');
var superagent = require('superagent');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

var ipList = [];
var ipIndex = 0;
var proxy = '';

function changeIp() {
    if (ipIndex < ipList.length - 1) {
        ipIndex += 1;
    } else {
        ipIndex = 0;
    }
    setProxy();
}

function setProxy() {
    var item = ipList[ipIndex];
    console.log(item);

    var ip = item.ip;
    var port = item.port;

    proxy = `http://${ip}:${port}`;
    console.log('proxy');

    console.log(proxy);

}

var connection1 = mysql.createConnection(mysqlProxy);
var query1 = 'select * from ip_table1 where (success_count>5 and error_count/success_count<0.8 )';
connection1.connect();
connection1.query(query1, function (err, res) {
    if (err) {
        console.log('query1 error');
        console.log(err);

    } else {
        ipList = res;
        console.log(ipList.length);
        setProxy();
        console.log(proxy);
        setInterval(() => {
            changeIp();
        }, 300 * 1000);
        getSong({ offset: 0 });
        // for (var i = 0; i < 1; i++) {
        //     var offset = 10 * i;
        //     fn1(offset);
        // }
    }
});
connection1.end();
getSong({ offset: 0 });
function getSong(options) {
    let offset = 0;
    if (options.offset) {
        offset = options.offset;
    }
    var connection2 = mysql.createConnection(mysqlCloudMusic);
    connection2.connect();

    var query2 = `SELECT * FROM song ORDER BY comment_version LIMIT 1 offset ${offset};`

    connection2.query(query2, function (err2, res2) {
        console.log('query2 end');
        if (err2) {
            console.log('query2 err');
            console.log(err2);

        } else {
            console.log('query2 success');
            if (res2.length < 0) {
                setTimeout(() => {
                    getSong({ offset: 0 });
                }, 3600 * 1000);
            } else {
                var song = res2[0];
                getComment(song);
            }
        }
    });
    connection2.end();
}

function getComment(song) {
    console.log(song);

    const songId = song.id;
    let url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_' + songId;
    superagent.get(url)
        .timeout(3000)
        .proxy(proxy)
        .end(function (err3, res3) {
            console.log('http end');
            console.log(proxy);
            console.log(url);
            if (err3) {
                console.log('http err');

                console.log(err3);
                // setTimeout(() => {

                // }, 2000);
                changeIp();
                getSong({ offset: 0 });
            } else {
                console.log('http success');
                // console.log(res3.text);

                let o = {};
                try {
                    o = JSON.parse(res3.text);
                } catch (error) {
                    // getSongList(limit, offset);
                    console.log(error);

                }
                let hotComments = [];
                hotComments = o.hotComments;
                if (typeof hotComments !== 'undefined') {
                    let commentCount = o.total;

                    if (hotComments.length > 0) {
                        var list1 = o.hotComments.map(v => {
                            var id = v.commentId;
                            var content = v.content;
                            var time = v.time;
                            var likedCount = v.likedCount;
                            // var songId = songId;

                            return [id, content, time, likedCount, songId];
                        });
                        const options = {
                            song: song,
                            commentList: list1,
                            commentCount: commentCount
                        }
                        upload(options);
                    } else {
                        console.log('没有热门评论');
                        console.log();
                        const options = {
                            song: song,
                            commentCount: commentCount
                        }
                        feedback(options);
                    }
                } else {
                    if (o.msg === '资源不存在') {

                    }
                    if (o.msg === 'Cheating') {
                        console.log('cheating');
                        setTimeout(() => {
                            changeIp();
                        }, 3000);
                    } else {

                    }
                }
            }
        })
}

function upload(options) {
    console.log(options);

    const song = options.song;
    const commentList = options.commentList;


    var connection = mysql.createConnection(mysqlCloudMusic);
    var queryString = 'replace into comment (id,content,time,liked_count,song_id) values ?';
    connection.connect();
    connection.query(queryString, [commentList], function (err, res) {
        if (err) {
            console.log('query3 err');
            console.log(err);
        } else {
            console.log(res);
            // onUploaded(songId);
            feedback(options);
        }
    });
    connection.end();
}

function feedback(options) {
    console.log('feedback');

    // console.log(options);

    const song = options.song;
    const songId = song.id;
    let commentVersion = song.comment_version;
    if (commentVersion) {
        commentVersion += 1;
    } else {
        commentVersion = 1;
    }
    const commentCount = options.commentCount;

    var query4 = `update song set comment_version=${commentVersion},comment_count=${commentCount} where id=${songId}`;
    console.log(query4);

    var connection4 = mysql.createConnection(mysqlCloudMusic);
    connection4.connect();
    connection4.query(query4, function (err, res) {
        if (err) {
            console.log(err);

        } else {
            console.log(res);
            setTimeout(() => {
                getSong({ offset: 0 });
            }, 2000);
        }
    });
    connection4.end();
}